const app = getApp();
const { sysInfo } = app.globalData;

Page({
  data: {
    sysInfo
  },
  onLoad (options) {
    this.drawImg();
  },
  onShow () {},
  onReachBottom () {},
  onPullDownRefresh () {},
  // 自定义方法
  async drawImg () {
    const { windowWidth, windowHeight, pixelRatio } = this.data.sysInfo;
    const width = windowWidth * pixelRatio;
    const height = windowHeight * pixelRatio;
    // 创建离屏 2D canvas 实例
    const canvas = wx.createOffscreenCanvas({
      type: '2d',
      width,
      height
    })
    // 获取 context。注意这里必须要与创建时的 type 一致
    const ctx = canvas.getContext('2d')
    // 旋转
    // ctx.translate(width * 0.5, height * 0.5);
    // ctx.rotate(-30 / 180 * Math.PI);
    // ctx.rect(0, 0, width, height)
    // ctx.setFillStyle('red')
    // ctx.fill()
    // ctx.draw()
    // 创建一个图片
    const image = canvas.createImage()
    // 等待图片加载
    await new Promise(resolve => {
      image.onload = resolve
      // 要加载的图片 url
      image.src = 'https://hn-jinggroup.gz.bcebos.com/v1/dev/2022/08/98925dbc-7054-4669-9b85-f5024bb17335.png'
    })
    // 把图片画到离屏 canvas 上
    // ctx.clearRect(0, 0, width, height)
    ctx.drawImage(image, 0, 0, 60, 15)
    // 再次旋转
    
    // 获取画完后的数据
    const imgData = ctx.getImageData(0, 0, 300, 200)
    console.log('imgData ==> ', imgData)
    wx.createSelectorQuery().select('#myCanvas').fields({
      node: true,
      size: true
    }).exec((res) => {
      console.log('res ====> ', res)
      const canvas2 = res[0].node;
      const ctx = canvas2.getContext('2d');
       // 将离屏Canvas的数据渲染到页面上的Canvas元素中
      ctx.putImageData(imgData, 0, 0);
    });
  }
});
